package com.qk.management.task;

import com.aliyun.oss.model.OSSObjectSummary;
import com.qk.management.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/*
 *  @author SHCJ
 *  @created 2025/10/11 20:51
 *  @description
 */
@Component
public class OSSTask {
    @Autowired
    private OssFileLister ossFileLister;
    @Autowired
    private OssDelete ossDelete;
    @Autowired
    private UserMapper userMapper;
//    每秒执行一次
//    @Scheduled(cron = "0/10 * * * * ?")
    public void clean() {
        System.out.println("OSSTask.run()");
        List<String > ossObjectSummaries = ossFileLister.listFiles();
        List<String> imgUrlAll = userMapper.getImgUrlAll();
        List<String> fileNameList = new ArrayList<>();

        for (String url : imgUrlAll) {
            // 找到最后一个"/"的位置
            int lastIndex = url.lastIndexOf("/");
            // 如果存在"/"且不是最后一个字符，则截取后面的部分
            if (lastIndex != -1 && lastIndex < url.length() - 1) {
                String fileName = url.substring(lastIndex + 1);
                fileNameList.add(fileName);
            } else {
                // 处理没有"/"的情况，这里直接添加原字符串，也可根据需求调整
                fileNameList.add(url);
            }
        }

        for (String ossObjectSummary : ossObjectSummaries) {
            if (!fileNameList.contains(ossObjectSummary)) {
                ossDelete.deleteFile(ossObjectSummary);
                System.out.println("删除文件：" + ossObjectSummary);
            }
        }
    }
}
